﻿using AiMoWindows.Windows.Themes;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Rendering;
using Microsoft.CodeAnalysis.Text;
using System.Windows.Media;

namespace AiMoWindows.Windows.Scripts.ViewModels
{
    class TextMatchHighlightRenderer : IBackgroundRenderer
    {
        private readonly TextView _textView;
        public KnownLayer Layer => KnownLayer.Selection;
        private readonly Brush _backgroundBrush;
        public TextMatchHighlightRenderer(TextView textView, DarkHighlightColors darkHighlightColors)
        {
            _textView = textView;
            _backgroundBrush = darkHighlightColors.GetBrush("selected text matching").Background.GetBrush(null);
            textView.BackgroundRenderers.Add(this);
        }
        TextSpan[]? Spans;

        public void SetSpans(IEnumerable<TextSpan>? spans)
        {
            if (spans == null)
            {
                Spans = null;
            }
            else
            {
                Spans = spans.ToArray();
                _textView.InvalidateLayer(Layer);
            }
        }

        public void Draw(TextView textView, DrawingContext drawingContext)
        {
            if (Spans == null) return;
            BackgroundGeometryBuilder builder = new BackgroundGeometryBuilder()
            {
                CornerRadius = 1,
                AlignToWholePixels = true,
            };
            foreach (TextSpan span in Spans)
            {
                builder.AddSegment(textView, new TextSegment()
                {
                    StartOffset = span.Start,
                    Length = span.Length,
                    EndOffset = span.End,
                });
                builder.CloseFigure();
            }

            var geometry = builder.CreateGeometry();
            if (geometry != null)
            {
                drawingContext.DrawGeometry(_backgroundBrush, null, geometry);
            }
        }
    }
}
